package com.aboo.infrastructure.base.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import java.io.IOException;
import java.util.Random;

/**
 * @ClassName MdcFilter
 * @Description
 * @Author louan
 * @Date 2021/3/18
 */
@Slf4j
public class MdcTraceFilter implements Filter {

    public static final String MDC_TRACE_ID_NAME = "MDC_TRACE_ID";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String mdcTraceId = req.getHeader(MDC_TRACE_ID_NAME);
        if (mdcTraceId == null || mdcTraceId.length() == 0) {
            mdcTraceId = String.format("%03d", new Random().nextInt(100)) + "." + System.currentTimeMillis();
        }
        MDC.put(MDC_TRACE_ID_NAME, mdcTraceId);
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

}
